package com.weacar.weixin.service;

import com.weacar.weixin.dao.UserDao;
import com.weacar.weixin.model.User;
import com.weacar.weixin.util.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Fong
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Override
    public User subscribe(String fromUserName) throws Exception {
        try {

            User user = new User();
            user.setName(fromUserName);
            user.setStatus("subscribed");
            userDao.save(user);
            return user;
        } catch (Exception e) {
            LogUtils.errorException(log, "userName="+fromUserName, e);
            throw new InternalServiceException("User subscribe error!");
        }
    }

    @Override
    public void unsubscribe(String fromUserName) throws Exception {
        try {
            User user = new User();
            user.setName(fromUserName);
            user.setStatus("unsubscribed");
            userDao.update(user);
        } catch (Exception e) {
            LogUtils.errorException(log, "userName="+fromUserName, e);
            throw new InternalServiceException("User subscribe error!");
        }
    }

    @Override
    public Optional<User> getUser(String fromUserName) {
        try {
            User user = userDao.queryByUser(fromUserName);
            if (user == null) {
                return Optional.empty();
            }
            return Optional.of(user);
        } catch (Exception e) {
            LogUtils.errorException(log, "userName="+fromUserName, e);
            throw new InternalServiceException("GetUser error!");
        }
    }

    @Override
    public void resubscribe(User user) {
        try {
            user.setStatus("subscribed");
            userDao.update(user);
        } catch (Exception e) {
            LogUtils.errorException(log, "userName="+user.getName(), e);
            throw new InternalServiceException("User resubscribe error!");
        }
    }
}
